import React, { useEffect, useState, useMemo } from 'react';
import { Input, Tag, Empty, Spin } from 'antd';
import { SearchOutlined, LeftOutlined, FireOutlined } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import { listBookByPage } from '../../api/bookController';
import { listPostByPage } from '../../api/communityPostController';
import { BookType } from '../../types/book';
import { PostType } from '../../types/post';
import { debounce } from 'lodash';

const SearchPage: React.FC = () => {
  const [searchTags, setSearchTags] = useState<string[]>(() => {
    const savedTags = localStorage.getItem('searchHistory');
    return savedTags ? JSON.parse(savedTags) : [];
  });
  
  const [hotPosts, setHotPosts] = useState<PostType[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchResults, setSearchResults] = useState<BookType[]>([]);
  const [searchVisible, setSearchVisible] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  
  const location = useLocation();
  const navigate = useNavigate();

  const searchParams = new URLSearchParams(location.search);
  const keyword = searchParams.get('keyword') || '';

  useEffect(() => {
    fetchHotPosts();
  }, []);

  // 节流处理的搜索函数
  const debouncedSearch = useMemo(
    () =>
      debounce(async (value: string) => {
        if (!value.trim()) {
          setSearchResults([]);
          return;
        }
        
        try {
          const response = await listBookByPage({
            current: 1,
            pageSize: 8,
            bookname: value,
            bookauthor: "",
            categorycode: ["all"]
          });
          
          if (response.code === 200) {
            setSearchResults(response.data.records);
          }
        } catch (error) {
          console.error('Search error:', error);
        }
      }, 300),
    []
  );

  // 处理搜索输入
  const handleSearchInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchValue(value);
    debouncedSearch(value);
    setSearchVisible(true);
  };

  // 处理选择搜索结果
  const handleSelectResult = (book: BookType) => {
    setSearchVisible(false);
    setSearchValue("");
    setSearchResults([]);
    
    // 保存搜索历史
    if (!searchTags.includes(book.bookname)) {
      const newTags = [book.bookname, ...searchTags].slice(0, 10);
      setSearchTags(newTags);
      localStorage.setItem('searchHistory', JSON.stringify(newTags));
    }
    
    navigate(`/book/${book.id}`);
  };

  // 高亮搜索关键词
  const highlightText = (text: string, keyword: string) => {
    if (!keyword.trim()) return text;
    const parts = text.split(new RegExp(`(${keyword})`, 'gi'));
    return (
      <span>
        {parts.map((part, index) => 
          part.toLowerCase() === keyword.toLowerCase() ? (
            <span key={index} className="text-red-400 font-medium">{part}</span>
          ) : (
            part
          )
        )}
      </span>
    );
  };

  const fetchHotPosts = async () => {
    setLoading(true);
    try {
      const response = await listPostByPage({
        current: 1,
        pageSize: 8,
        title: '',
        content: '',
        categorycode: ''
      });
      
      if (response.code === 200) {
        // 按照浏览量排序
        const sortedPosts = response.data.records.sort((a: PostType, b: PostType) => b.viewcount - a.viewcount);
        setHotPosts(sortedPosts);
      }
    } catch (error) {
      console.error('获取热门帖子失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleTagClose = (removedTag: string) => {
    const newTags = searchTags.filter(tag => tag !== removedTag);
    setSearchTags(newTags);
    localStorage.setItem('searchHistory', JSON.stringify(newTags));
  };

  // 添加回车搜索处理函数
  const handleEnterSearch = () => {
    if (searchValue.trim()) {
      if (!searchTags.includes(searchValue.trim())) {
        const newTags = [searchValue.trim(), ...searchTags].slice(0, 10);
        setSearchTags(newTags);
        localStorage.setItem('searchHistory', JSON.stringify(newTags));
      }
      debouncedSearch(searchValue);
      setSearchVisible(true);
    }
  };

  return (
    <div className="max-w-7xl mx-auto p-4">
      {/* 返回按钮 */}
      <div className="mb-4 flex justify-between bg-white p-2 rounded-md">
        <LeftOutlined 
          className="text-xl cursor-pointer hover:text-blue-500"
          onClick={() => navigate(-1)}
        />
        <p>返回上一界面</p>
        <div></div>
      </div>

      {/* 搜索框和下拉列表 */}
      <div className="mb-8 relative">
        <Input
          placeholder="搜索图书..."
          value={searchValue}
          onChange={handleSearchInput}
          onPressEnter={handleEnterSearch}
          onBlur={() => {
            setTimeout(() => setSearchVisible(false), 200);
          }}
          onFocus={() => {
            if (searchValue) setSearchVisible(true);
          }}
          prefix={<SearchOutlined />}
          className="w-full text-lg"
          size="large"
        />
        
        {searchVisible && searchResults.length > 0 && (
          <div className="absolute z-50 w-full mt-1 bg-white rounded-md shadow-lg max-h-[400px] overflow-y-auto">
            {searchResults.map((book) => (
              <div
                key={book.id}
                className="px-4 py-3 hover:bg-gray-100 cursor-pointer"
                onClick={() => handleSelectResult(book)}
              >
                <div className="flex items-center">
                  <img 
                    src={book.imageurl} 
                    alt={book.bookname}
                    className="w-10 h-10 object-cover rounded mr-2"
                  />
                  <div>
                    <div className="font-medium">
                      {highlightText(book.bookname, searchValue)}
                    </div>
                    <div className="text-sm text-gray-500">
                      {book.bookauthor}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 搜索历史标签 */}
      <div className="mb-8">
        <h2 className="text-lg font-bold mb-4">搜索历史</h2>
        <div className="flex flex-wrap gap-2">
          {searchTags.map((tag) => (
            <Tag
              key={tag}
              closable
              onClose={() => handleTagClose(tag)}
              onClick={() => {
                setSearchValue(tag);
                debouncedSearch(tag);
                setSearchVisible(true);
              }}
              className="cursor-pointer"
            >
              {tag}
            </Tag>
          ))}
        </div>
      </div>

      {/* 热门帖子 */}
      <div>
        <h2 className="text-lg font-bold mb-4">热门帖子</h2>
        <Spin spinning={loading}>
          {hotPosts.length > 0 ? (
            <div className="grid gap-1">
              {hotPosts.map((post, index) => (
                <div
                  key={post.id}
                  onClick={() => navigate(`/community/all/post/${post.id}`)}
                  className="flex items-center justify-between px-4 py-3 bg-white rounded-md cursor-pointer hover:bg-gray-50 transition-colors"
                >
                  <div className="flex-1 min-w-0 mr-4">
                    <div className="text-base truncate">
                      {post.title}
                    </div>
                  </div>
                  <div className="flex items-center whitespace-nowrap">
                    <span className="text-gray-500 mr-2">
                      {post.viewcount} 浏览
                    </span>
                    {index < 3 && (
                      <FireOutlined 
                        className={
                          index === 0 ? 'text-red-500' :
                          index === 1 ? 'text-orange-500' :
                          'text-yellow-500'
                        }
                      />
                    )}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <Empty description="暂无热门帖子" />
          )}
        </Spin>
      </div>
    </div>
  );
};

export default SearchPage;